<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2019/4/8
 * Time: 15:17
 */

namespace common\logics\peppercash;

use common\widgets\Tool;
use Yii;
use yii\base\BaseObject;

class PepperCashLogic extends BaseObject implements IPepperCash
{
    /** @var \common\sources\read\peppercash\PepperCashAccess $RPepperCashAccess***/
    private $RPepperCashAccess;
    /** @var \common\sources\read\buyuser\BuyUserAccess  $RBuyUserAccess ***/
    private $RBuyUserAccess;
    /** @var \common\sources\read\buyuser\BuyUserAcountAccess  $RBuyUserAcountAccess **/
    private $RBuyUserAcountAccess;
    /** @var \common\sources\write\buyuser\BuyUserAcountAccess $WBuyUserAcountAccess  **/
    private $WBuyUserAcountAccess;
    /** @var \common\sources\write\peppercash\PepperCashAccess  $WPepperCashAccess ***/
    private $WPepperCashAccess;
    /** @var \common\sources\read\bank\BankAccess  $RBankAccess  **/
    private $RBankAccess;
    /** @var \common\sources\write\pepperrecord\PepperRecordAccess $WPepperRecordAccess **/
    private $WPepperRecordAccess;

    public function init()
    {
        $this->RPepperCashAccess = Yii::$container->get("RPepperCashAccess");
        $this->RBuyUserAccess = Yii::$container->get("RBuyUserAccess");
        $this->RBuyUserAcountAccess = Yii::$container->get("RBuyUserAcountAccess");
        $this->WBuyUserAcountAccess = Yii::$container->get("WBuyUserAcountAccess");
        $this->WPepperCashAccess = Yii::$container->get("WPepperCashAccess");
        $this->RBankAccess = Yii::$container->get("RBankAccess");
        $this->WPepperRecordAccess = Yii::$container->get("WPepperRecordAccess");
        parent::init();
    }

    public function getList($data)
    {
        if(empty($data['buy_id']))
        {
            return Tool::returnJson([],401,"买手用户id不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],402,"安全码不能为空");
        }
        if(md5($data['buy_id']) != $data['safetyCode'])
        {
            return Tool::returnJson([],403,"安全码不正确");
        }
        $count = $this->RPepperCashAccess->getCount($data);
        $list = [];
        if($count >0)
        {
            $list = $this->RPepperCashAccess->getList($data);
            foreach ($list as &$item)
            {
                $item['create_time'] = isset($item['create_time']) ? date('Y-m-d H:i:s',$item['create_time']) : '';
                $item['status_name'] = isset($item['status']) ? Yii::$app->params['pepper_cash_record_status'][$item['status']]:'未知状态';

            }
        }
        return Tool::returnJson([
            "list" => $list,
            "count" => $count,
            "page_num" => $data['page_num'],
        ],200,"成功");
    }

    public function revoke($data)
    {
        if(empty($data['buy_id']))
        {
            return Tool::returnJson([],401,"买手id不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],402,"安全码不能为空");
        }
        if(md5($data['buy_id'].$data['pepper_cash_id']) != $data['safetyCode'])
        {
            return Tool::returnJson([],403,"安全码不正确");
        }
        if(empty($data['pepper_cash_id']))
        {
            return Tool::returnJson([],405,"花椒提现id不能为空");
        }
        $pepper_cash = $this->RPepperCashAccess->getPepperCashById($data['pepper_cash_id']);
        if(empty($pepper_cash))
        {
            return Tool::returnJson([],406,"花椒提现记录不存在");
        }
        if($pepper_cash['status'] !=1)
        {
            return Tool::returnJson([],407,"花椒提现记录不撤销");
        }
        $buyUser = $this->RBuyUserAccess->getBuyUserInfo($data['buy_id']);
        if(empty($buyUser))
        {
            return Tool::returnJson([],408,"买手用户不存在");
        }
        $buy_account = $this->RBuyUserAcountAccess->getBuyUserAccount($data['buy_id']);
        if(empty($buy_account))
        {
            return Tool::returnJson([],409,"账号信息不存在");
        }
        if($pepper_cash['status'] !=1)
        {
            return Tool::returnJson([],410,"非待审核提现花椒不能取消");
        }

        $transaction = Yii::$app->db->beginTransaction();
        try{
            $arr = [
                "status" => 6,
                "id" =>$data['pepper_cash_id']
            ];
            $res = $this->WPepperCashAccess->modifyPepperCash($arr);
            if($res)
            {
                $buy_arr = [
                    "remail_golds" => number_format($buy_account['remail_golds'] + $pepper_cash['money'],2,".",""),
                    "freezing_golds" => number_format($buy_account['freezing_golds'] - $pepper_cash['money'],2,".",""),
                    "buy_id" => $data['buy_id']
                ];
                $res_pepper = $this->WBuyUserAcountAccess->modifyPepperUserAccount($buy_arr);
                if(!$res_pepper)
                {
                    $transaction->rollBack();
                    return Tool::returnJson([],411,"修改买手花椒失败");
                }
                //增加花椒记录
                $pepper_arr = [
                    "type" =>3,
                    "expend" => 0,
                    "income" => $pepper_cash['money'],
                    "balance" =>number_format($buy_account['remail_golds'] + $pepper_cash['money'],2,".",""),
                    "freeze_change" =>  -$pepper_cash['money'],
                    "freeze_balance" => number_format($buy_account['freezing_golds'] - $pepper_cash['money'],2,".",""),
                    "remark" => "撤销花椒提现返还+".$pepper_cash['money'],
                    "buy_id" => $data['buy_id']
                ];
               $res_pepper = $this->WPepperRecordAccess->addPepperRecord($pepper_arr);
               if(!$res_pepper)
               {
                   $transaction->rollBack();
                   return Tool::returnJson([],412,"增加花椒记录失败");
               }
                $transaction->commit();
                return Tool::returnJson([],200,"撤销成功");
            }
            $transaction->rollBack();
            return Tool::returnJson([],413,"撤销失败");
        }catch (\Exception $e)
        {
            $transaction->rollBack();
            return Tool::returnJson([],5000,"撤销异常");
        }
    }

    public function applyCash($data)
    {
        if(empty($data['buy_id']))
        {
            return Tool::returnJson([],401,"买手id不能为空");
        }
        if(empty($data['money']))
        {
            return Tool::returnJson([],402,"申请提现金额不能为空");
        }
        if(empty($data['pay_pwd']))
        {
            return Tool::returnJson([],403,"申请提现密码不能为空");
        }
        $buyer = $this->RBuyUserAccess->getBuyUserInfo($data['buy_id']);
        if(empty($buyer))
        {
            return Tool::returnJson([],405,"买手账号不存在");
        }
        $buyAccount = $this->RBuyUserAcountAccess->getBuyUserAccount($data['buy_id']);
        if(empty($buyAccount))
        {
            return Tool::returnJson([],406,"买手账号信息不能存在");
        }
        if(empty($buyer['paypwd']) || $buyer['is_pay'] == 0)
        {
            return Tool::returnJson([],407,"没有设置提现密码");
        }
        //验证密码
        if (!Yii::$app->security->validatePassword($data['pay_pwd']."", $buyer['paypwd'])) {
            return Tool::returnJson([], 408, '提现密码错误');
        }
        if($buyAccount['remail_golds'] < $data['money'])
        {
            return Tool::returnJson([], 409, '提现花椒大于可用花椒');
        }
        $band_account = $this->RBankAccess->getBuyUserBankAccount($data['buy_id']);
        if(empty($band_account))
        {
            return Tool::returnJson([], 410, '该买手没有绑定提现信息');
        }
        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $cash_num = "ST".date('YmdHis',time());
            $arr = [
                "buy_id" => $data['buy_id'],
                "cash_num" => $cash_num,
                "money" => $data['money'],
                "cash_money" => number_format($data['money']*0.9,2,".",""),
                "status" => 1,
                "remark" => "银行转账预计需要1-3个工作日，请等待转账",
                "real_name" => $band_account['real_name'],
                "account_num" => $band_account['cardnum'],
            ];
            $res = $this->WPepperCashAccess->addPepperCash($arr);
            if($res)
            {
                $buy_arr = [
                    "remail_golds" => number_format($buyAccount['remail_golds']- $data['money'],2,".",""),
                    "freezing_golds" => number_format($buyAccount['freezing_golds'] + $data['money'],2,".",""),
                    "buy_id" => $data['buy_id'],
                ];
                $buy_res = $this->WBuyUserAcountAccess->modifyPepperUserAccount($buy_arr);
                if($buy_res)
                {
                    //增加花椒记录
                    $pepper_arr = [
                        "type" =>2,
                        "expend" => $data['money'],
                        "income" => 0,
                        "balance" =>number_format($buyAccount['remail_golds']- $data['money'],2,".",""),
                        "freeze_change" =>  $data['money'],
                        "freeze_balance" => number_format($buyAccount['freezing_golds'] + $data['money'],2,".",""),
                        "remark" => "申请提现花椒扣减花椒-".$data['money'],
                        "buy_id" => $data['buy_id']
                    ];
                    $res_pepper = $this->WPepperRecordAccess->addPepperRecord($pepper_arr);
                    if(!$res_pepper)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],412,"增加花椒记录失败");
                    }

                    $transaction->commit();
                    return Tool::returnJson([],200,"成功");
                }
                $transaction->rollBack();
                return Tool::returnJson([],411,"申请提现失败");
            }
            $transaction->rollBack();
            return Tool::returnJson([],411,"申请提现失败");
        }catch (\Exception $e)
        {
            $transaction->rollBack();
            return Tool::returnJson([],411,"申请提现异常".$e->getMessage());
        }
    }

}